import re, logging, json

from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib.auth import login, authenticate, logout
from django.views import View
from django import http
from django_redis import get_redis_connection
from django.contrib.auth.mixins import LoginRequiredMixin


from pymysql import DatabaseError
from users.models import User
from meiduo_mall.utils.response_code import RETCODE

from celery_tasks.email.tasks import send_verify_email
from users.utils import generate_verify_email_url, check_verify_email_token
from meiduo_mall.utils.views import LoginRequiredJsonMixin
from goods import models
from . import constants
from users.models import Address
from carts.utils import merge_cart_cookie_to_redis
logger = logging.getLogger('django')


class UserBrowseHistory(LoginRequiredJsonMixin, View):
    """用户浏览记录"""
    def get(self, request):
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s'%request.user.id, 0, -1)

        skus = []
        for sku_id in sku_ids:
            sku = models.SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': skus})

    def post(self, request):
        """保存用户商品浏览记录"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        try:
            models.SKU.objects.get(id=sku_id)
        except models.SKU.DoesNotExist:
            return http.HttpResponseForbidden('参数sku_id参数错误')

        redis_conn = get_redis_connection('history')
        p1 =redis_conn.pipeline()
        user_id =request.user.id
        # 先去重
        p1.lrem('history_%s'%user_id, 0, sku_id)
        # 再添加
        p1.lpush('history_%s'%user_id,sku_id)
        # 取前四个
        p1.ltrim('history_%s'%user_id, 0, 4)
        # 执行
        p1.execute()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class UpdateTitleAddressView(LoginRequiredJsonMixin, View):
    """设置地址标题"""

    def put(self, request, address_id):
        """实现更新地址标题逻辑"""
        json_dict = json.loads(request.body.decode())

        title = json_dict.get('title')

        if not title:
            return http.HttpResponseForbidden('缺少title')
        try:
            # 查询当前要更新标题的地址
            address = Address.objects.get(id=address_id)
            # 修改地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})

        # 4.响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})


class DefaultAddressView(LoginRequiredJsonMixin, View):
    """设置默认地址, 需要用户登录"""

    def put(self, request, address_id):
        """实现设置默认地址逻辑"""
        try:
            """实现设置默认地址逻辑"""
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})


class UpdateDestroyAddressView(LoginRequiredJsonMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')
        # 使用最新的地址信息覆盖指定的就得地址信息
        # address = Address.objects.get(id=address_id)
        # address.title = ''
        # address.user = ''
        # address.save()
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':RETCODE.DBERR, 'errmsg': '修改地址失败'})

        # 响应新的地址信息给前端进行渲染
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 响应新的地址信息给前端进行渲染
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        # 接收参数
        try:
            # 查询要删除的地址   Address.objects.get() 返回值是一个对象
            address = Address.objects.get(id=address_id)
            address.is_deleted=True
            address.save()

            if request.user.default_address_id == address_id:
                # request.user 是登陆的用户，可以直接修改表内容，也需要用save保存
                request.user.default_address = None
                request.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})


class CreateAddressView(LoginRequiredJsonMixin, View):

    def post(self, request):
        # 判断是否超过地址上限：最多20个
        # Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())

        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')
        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            # 如果登录用户没有默认的地址, 我们需要将当前的地址指定为默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 构造返回字典数据
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,  # address.province返回的是实例方法  name是属性，返回城市的名字
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 响应保存结果   "default_address_id":request.user.default_address_id 将默认地址返回
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功','address': address_dict,
                                  "default_address_id":request.user.default_address_id})


class AddressView(LoginRequiredMixin, View):

    def get(self, request):
        # 询问用户的收货地址
        # Address.objects.filter(user=request.user, is_deleted=False)
        # 使用当前登录用户和is_deleted=False作为条件查询地址数据
        addresses = request.user.addresses.filter(is_deleted=False)

        address_list =[]
        for address in addresses:

            address_dirct = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,  # 展示name字段信息
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_list.append(address_dirct)

        context = {
            'default_address_id': request.user.default_address_id,
            'addresses': address_list
        }
        return render(request, 'user_center_site.html',context)


class VerifyEmailView(View):
    """验证邮箱"""

    def get(self, request):

        token = request.GET.get('token')
        # 校验参数
        if not token:
            return http.HttpResponseForbidden('缺少token')

        # 从token中提取用户信息user_id ==> user
        user = check_verify_email_token(token)

        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('激活邮件失败')

        return redirect(reverse('users:info'))


class EmailView(LoginRequiredJsonMixin, View):
    """添加邮箱"""
    def put(self, requset):
        # 接受参数
        json_dict = json.loads(requset.body.decode())
        email = json_dict.get('email')
        # 校验参数
        if not email:
            return http.HttpResponseForbidden('缺少email参数')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')
        # 将参数写入数据库
        try:
            requset.user.email = email
            requset.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})
        # 异步发送验证邮件
        verify_url = generate_verify_email_url(requset.user)
        send_verify_email.delay(email, verify_url)

        # 响应添加邮箱结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})


class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):

        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active,
        }

        return render(request, 'user_center_info.html', context)


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        """
        实现退出登录逻辑
        """

        # 清除状态保持信息
        logout(request)

        # 退出登录，重定向到首页
        response = redirect(reverse('contents:index'))
        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


# Create your views here.
class LoginView(View):
    def get(self,request):
        return render(request, 'login.html')

    def post(self,request):

        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        if not all([username, password]):
            return http.HttpResponseForbidden('缺少必传参数')

        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入正确的用户名或手机号')

        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')

        # 认证登录用户
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        # 实现状态保持
        login(request, user)
        # 设置状态保持的周期
        if remembered != 'on':
            # 没有记住登录：状态保持在浏览器会话结束后就销毁
            request.session.set_expiry(0)
        else:
            # 记住登录：状态保持周期默认为两周
            request.session.set_expiry(None)

        # 相应登录结果
        red = request.GET.get('next')
        # 判断是否获取到'next'，获取到就返回会next设定的网页
        if red:
            response = redirect(red)
        else:
            response = redirect(reverse('contents:index'))

        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
        return response


class UserPhone(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile= mobile).count()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','count':count})


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username = username).count()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','count':count})


class RegisterView(View):

    def get(self,request):

        return render(request,'register.html')

    def post(self,request):
        # POST接收表单数据
        value = request.POST.get('key')
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        sms_code_client = request.POST.get('sms_code')

        # any(列表)，只要一个为true,就为true
        # 判断参数是否齐全：all(列表)，只要有一个为false就返回false，这里判断是否为空
        if not all([username,password,password2,mobile,allow]):
            return http.HttpResponseForbidden('缺少必传参数')

        # match判断阐述是否齐全
        # re.search扫描整个字符串并返回第一个成功的匹配
        if not re.match(r'^\w{5,20}$',username):
            return http.HttpResponseForbidden('请输入5-20字符的用户名')
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 勾选默认返回'on'
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s'%mobile)

        if sms_code_server is None:
            return render(request,'register.html', {'sms_code_errmsg': '短信验证码已失效'})
        if sms_code_client != sms_code_server.decode():
            return render(request,'register.html', {'sms_code_errmsg': '短信验证码错误'})


        # 测试是返回是否成功
        # return render(request, 'register.html', {'register_error': '注册失败'})

        try:
            # 将数据写入数据库
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except DatabaseError:
            return render(request,'register.html',{'register_errmsg':'注册失败'})
        login(request, user)

        response = redirect(reverse('contents:index'))

        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


